/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.alien.admin.modules.deploy.service.impl;

import com.alien.admin.modules.deploy.domain.ServerPort;
import com.alien.admin.utils.ValidationUtil;
import com.alien.admin.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.alien.admin.modules.deploy.repository.ServerPortRepository;
import com.alien.admin.modules.deploy.service.ServerPortService;
import com.alien.admin.modules.deploy.service.dto.ServerPortDto;
import com.alien.admin.modules.deploy.service.dto.ServerPortQueryCriteria;
import com.alien.admin.modules.deploy.service.mapstruct.ServerPortMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.alien.admin.utils.PageUtil;
import com.alien.admin.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zhouseyi
* @date 2021-10-28
**/
@Service
@RequiredArgsConstructor
public class ServerPortServiceImpl implements ServerPortService {

    private final ServerPortRepository serverPortRepository;
    private final ServerPortMapper serverPortMapper;

    @Override
    public Map<String,Object> queryAll(ServerPortQueryCriteria criteria, Pageable pageable){
        Page<ServerPort> page = serverPortRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(serverPortMapper::toDto));
    }

    @Override
    public List<ServerPortDto> queryAll(ServerPortQueryCriteria criteria){
        return serverPortMapper.toDto(serverPortRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ServerPortDto findById(Integer id) {
        ServerPort serverPort = serverPortRepository.findById(id).orElseGet(ServerPort::new);
        ValidationUtil.isNull(serverPort.getId(),"ServerPort","id",id);
        return serverPortMapper.toDto(serverPort);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerPortDto create(ServerPort resources) {
        return serverPortMapper.toDto(serverPortRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ServerPort resources) {
        ServerPort serverPort = serverPortRepository.findById(resources.getId()).orElseGet(ServerPort::new);
        ValidationUtil.isNull( serverPort.getId(),"ServerPort","id",resources.getId());
        serverPort.copy(resources);
        serverPortRepository.save(serverPort);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            serverPortRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ServerPortDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ServerPortDto serverPort : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("服务名称", serverPort.getServer());
            map.put("端口", serverPort.getPort());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public ServerPortDto generateServerNodePort(String projectName, String env) {
        String serverName = String.format("%s-%s", projectName, env);
        ServerPortQueryCriteria criteria = new ServerPortQueryCriteria();
        criteria.setServer(serverName);

        List<ServerPortDto> serverPortDtoList = queryAll(criteria);
        if(serverPortDtoList == null || serverPortDtoList.isEmpty()) {
            // 查找最大端口
            Integer maxPort = serverPortRepository.findMaxNodePort();
            if(maxPort == null) {
                maxPort = 30000;
            }

            maxPort++;

            ServerPortDto serverPortDto = new ServerPortDto();
            serverPortDto.setPort(maxPort);
            serverPortDto.setServer(serverName);

            return create(serverPortMapper.toEntity(serverPortDto));
        }

        return serverPortDtoList.get(0);
    }
}
